package com.nicmic.blog.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nicmic.blog.dto.ResultBody;
import com.nicmic.blog.pojo.User;
import com.nicmic.blog.service.UserService;

/**
 * 
 * @author nicmic
 * @date 2016-08-24 11:54:57
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService service;
	
	@ResponseBody
	@RequestMapping("/insert")
	private ResultBody insert(@ModelAttribute User user){
		ResultBody body = new ResultBody();
		
		user.setId(UUID.randomUUID().toString());
		Date date = new Date(System.currentTimeMillis());
		user.setCreatedAt(date);
		user.setUpdatedAt(date);
		System.out.println(user.toString());
		
		service.add(user);
		
		body.setCode(1);
		body.setMsg("����ɹ�");
		body.setData(user);
		
		return body;
	}
	
	@ResponseBody
	@RequestMapping("/get")
	private ResultBody get(@RequestParam("username") String username){
		ResultBody body = new ResultBody();
		System.out.println("Ҫ��ѯ���û�����" + username);
		List<User> users = service.get(username);
		
		body.setCode(1);
		body.setMsg("�ɹ�");
		body.setData(users);
		System.out.println("��ѯ�Ľ����" + users.toString());
		
		return body;
	}
	
	@ResponseBody
	@RequestMapping("/delete")
	private ResultBody delete(@RequestParam("username") String username){
		ResultBody body = new ResultBody();
		System.out.println("Ҫɾ�����û�����" + username);
		int column = service.delete(username);
		
		if(column == 0){
			body.setCode(0);
			body.setMsg("ɾ��ʧ�ܣ�Ҫɾ�����û�������");	
		}else {
			body.setCode(1);
			body.setMsg("��ɾ����" + column + "����¼");		
		}
	
		return body;
	}
	
	@ResponseBody
	@RequestMapping("/update")
	private ResultBody update(@ModelAttribute User user){
		ResultBody body = new ResultBody();
		System.out.println("要修改的用户信息：\n" + user.toString());
		int column = service.update(user);
		if (column == 0) {
			body.setCode(0);
			body.setMsg("修改失败");
		}else{
			body.setCode(1);
			body.setMsg("修改成功，影响了" + column + "条记录");
		}
		
		return body;
	}
	
}
